package cn.com.wxd.service.freemarker.core;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * Title:模板读取核心类
 * Description:cn.com.wxd.service.freemarker
 * <p>
 * Company: 读取模板类
 * Copyright: Copyright (c) 2015
 * All right reserved.
 * Created time: 2016-4-12 上午11:32:40
 *
 * @author WangXuDong
 * @version 1.0
 */
public class FreeMarker {
    private static final Logger log = LoggerFactory.getLogger(FreeMarker.class);
    private Configuration cfg;

    /**
     * 设置模板地址
     *
     * @param path
     */
    public FreeMarker(String path) {
        init(path);
    }

    private void init(String path) {
        //初始化FreeMarker配置
        //创建一个Configuration实例
        cfg = new Configuration();
        try {
            cfg.setDirectoryForTemplateLoading(new File(path));
        } catch (IOException e) {
            log.error("模板读取错误!" + e.getMessage(), e);
        }
    }

    public String process(String tempName, HashMap<String, String> data) {
        //创建模版对象
        if (!tempName.contains(".ftl")) {
            tempName = tempName + ".ftl";
        }
        Template t;
        try {
            t = cfg.getTemplate(tempName, "utf-8");
            //在模版上执行插值操作，并输出到制定的输出流中
            Writer out = new StringWriter(512);
            t.process(data, out);  //处理模板
            return out.toString();
        } catch (TemplateException e) {
            log.error("模板处理错误" + e.getMessage(), e);
        } catch (IOException e) {
            log.error("IO异常，输出模板错误:" + e.getMessage(), e);
        }
        return null;
    }

    /**
     * 获取模板处理后的模板字符串并输出到相应的文件中
     *
     * @param tempName 模板名称
     * @param data     模板处理时需要的数据
     * @param Filepath 输出的文件
     *
     * @return 处理后的模板数据
     *
     * @throws TemplateException
     * @throws IOException
     */
    public String processToFile(String tempName, HashMap<String, String> data, String filePath)
            throws TemplateException, IOException {
        //创建模版对象
        if (!tempName.contains(".ftl")) {
            tempName = tempName + ".ftl";
        }
        Template t;
        FileOutputStream out2 = null;
        try {
            t = cfg.getTemplate(tempName, "utf-8");
            //在模版上执行插值操作，并输出到制定的输出流中
            Writer out = new StringWriter(512);
            t.process(data, out);  //处理模板
            String htmlStr = out.toString();
            byte[] buff;
            buff = htmlStr.getBytes();
            File f = new File(filePath);
            if (f.isDirectory()) {
                filePath += File.separator + tempName + ".txt";
            } else {
                if (f.exists()) {
                    f.createNewFile();
                }
            }
            out2 = new FileOutputStream(filePath);
            out2.write(buff, 0, buff.length);
            return out.toString();
        } catch (TemplateException e) {
            log.error("模板处理错误" + e.getMessage(), e);
            throw e;
        } catch (IOException e) {
            log.error("IO异常，输出模板错误:" + e.getMessage(), e);
            throw e;
        } finally {
            out2.close();
        }
    }
}
